﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Classwork04
{
    //class Program
    //{
    //    static void Main(string[] args)
    //    {
    //    }
    //}

    public delegate void Alarm();

    public class Alarmer
    {
        public event Alarm Tick;
        public event Alarm Ring;

        private bool timeup;
        private int time;

        public void DoTick()
        {
            timeup = false;
            while (!timeup)
            {
                System.Threading.Thread.Sleep(1000);
                if (Tick != null)
                {
                    Tick();
                }
                time -= 1;
                if (time <= 0)
                    DoRing();
            }
        }

        public void DoRing()
        {
                
            Ring();
            timeup = true;
        }

        public void setTime(int _time)
        {
            time = _time;
        }
    }

    public class Receiver
    {
        public static void Main()
        {
            Console.WriteLine("这是一个闹钟！");
            Console.WriteLine("输入时间（秒）后响铃！");
            string s = " ";
            int n = 0;
            bool isok = false;
            while (!isok)
            {
                try
                {
                    isok = true;
                    s = Console.ReadLine();
                    n = Int32.Parse(s);
                    if (n <= 0)
                        throw new FormatException();
                }
                catch (FormatException)
                {
                    Console.WriteLine("请输入正整数！");
                    isok = false;
                }
            }
            

            var alarmer = new Alarmer();
            alarmer.setTime(n);
            alarmer.Tick += Ticking;
            alarmer.Ring += Ringing;
            alarmer.DoTick();

        }

        public static void Ticking()
        {
            Console.Write("滴答");
        }

        public static void Ringing()
        {
            Console.WriteLine();
            Console.WriteLine("时间到！");
        }
    }
}
